import React, { Fragment, ReactNode, Suspense } from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import type { RouteProps, RedirectProps } from 'react-router-dom';
import type { routesType } from '@/router/router';

const RouterView: React.FC<{ routes: routesType[] }> = function (props) {
  const { routes } = props;
  return (
    <Fragment>
      <Switch>
        {routes.map((item, index) => {
          let {
              redirect,
              exact,
              from,
              to,
              path,
              component: Component,
              name,
              meta,
            } = item,
            config: RouteProps = {},
            configredire: RedirectProps = { to: to ? to : '/404' };

          if (redirect) {
            if (from) configredire.from = from;
            if (exact) configredire.exact = true;
            return <Redirect key={index} {...configredire}></Redirect>;
          }

          config = { path };
          if (exact) config.exact = true;

          return (
            <Route
              key={index}
              {...config}
              render={(renderProps) => {
                // 统一基于render函数处理
                return (
                  <Suspense fallback={<>正在处理中...</>}>
                    {Component ? <Component {...renderProps} /> : <></>}
                  </Suspense>
                );
              }}
            ></Route>
          );
        })}
      </Switch>
    </Fragment>
  );
};

export default RouterView;
